#!/bin/bash

name="user_srv_main"

# 检查并确保 'user_srv_main' 文件有可执行权限
if [ ! -x ./$name ]; then
    echo "$name does not have execute permissions. Adding execute permissions..."
    chmod +x ./$name
fi

# 检查 log 目录是否存在，不存在则创建
if [ ! -d "./log" ]; then
    echo "Log directory does not exist. Creating ./log..."
    mkdir -p ./log
fi

# 获取 user_srv_main 进程的 PID（如果有的话）
PID=$(ps aux | grep $name | grep -v 'grep' | awk '{print $2}')

# 判断 PID 是否为空
if [ -z "$PID" ]; then
    # 如果没有找到进程，就执行
    echo "$name is not running. Starting it now..."
    nohup ./$name >> ./log/access_$(date +%Y-%m-%d).log 2>&1 &
else
    # 如果已经在运行，先杀掉进程，再执行
    echo "$name is already running. Killing the process (PID: $PID)..."
    kill $PID
    # 等待进程终止
    wait $PID
    # 执行新的进程
    echo "Starting $name again..."
    nohup ./$name >> ./log/access_$(date +%Y-%m-%d).log 2>&1 &
fi
